using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using EventUtils;
using UnityEngine;
using UnityEngine.UI;
using EventType = UnityEngine.EventType;
using Random = UnityEngine.Random;

namespace View.Instant
{
    public class Game1View : View
    {
        /// <summary>
        /// 底下7张牌
        /// </summary>
        public class MjCardInfo
        {
            public Image _img;
            public MJCS _csMj;
        }
        private class OptBtnInfo
        {
            public Button _btn;
            public GameObject _objHaveTimes;
            public Text _txtbacktimes;
            public GameObject _objAddTimes;
        }
        private Button mbtnStop;
        private GameObject mobjStart;
        private GameObject mobjStop;
        private Text mtxtCardNum;
        private Text mtxtTime;
        private Button mbtnAddTime;
        private GameObject mobjAddTime;
        // private Button mbtnClose;
        
        // private MjCardInfo[] mimgShowCard = new MjCardInfo[7];
        private OptBtnInfo[] mOptArr = new OptBtnInfo[5];
        
        private int[] mShowCardNumArr = new int[7];
        private List<MJCS> mFanpaiList = new List<MJCS>();
        
        // private bool mGamePause = false;
        private int mCardNum = 0;
        private int mGameTimer = 0;
        private Dictionary<PropItemEnum, int> mPropCountDic = new Dictionary<PropItemEnum, int>();
        public override void OnLoad()
        {
            base.OnLoad();

            mbtnStop = transform.Find("Up/stop").GetComponent<Button>();
            mobjStart = transform.Find("Up/stop/start").gameObject;
            mobjStop = transform.Find("Up/stop/stop").gameObject;
            mtxtCardNum = transform.Find("Up/mj/txtCount").GetComponent<Text>();
            mtxtTime = transform.Find("Up/time/txtTime").GetComponent<Text>();
            mbtnAddTime = transform.Find("Up/time").GetComponent<Button>();
            mobjAddTime = transform.Find("Up/time/jia").gameObject;
            // mbtnClose = transform.Find("Up/btnback").GetComponent<Button>();

            // for (int i = 0; i < mimgShowCard.Length; i++)
            // {
            //     mimgShowCard[i] = new MjCardInfo();
            //     mimgShowCard[i]._img = transform.Find("down/ShowCard/" + (i + 1)+"/img").GetComponent<Image>();
            //     var mjobj = transform.Find("down/ShowCard/" + (i + 1)+"/mj2").gameObject;
            //     var mjcs = mjobj.AddComponent<MJCS>();
            //     mjcs.OnInit(mjobj.transform.parent,mjobj.transform.parent,MJCtrl.Instance().OnGetMaterialBymjId(1),0,0);
            //     mimgShowCard[i]._csMj = mjcs;
            // }
            for (int i = 0; i < mOptArr.Length; i++)
            {
                mOptArr[i] = new OptBtnInfo();
                mOptArr[i]._btn = transform.Find("down/btn" + (i + 1)).GetComponent<Button>();
                mOptArr[i]._objHaveTimes = transform.Find("down/btn" + (i + 1)+"/have").gameObject;
                mOptArr[i]._txtbacktimes = transform.Find("down/btn" + (i + 1)+"/have/backTimes").GetComponent<Text>();
                mOptArr[i]._objAddTimes = transform.Find("down/btn" + (i + 1)+"/add").gameObject;
            }
            
            mPropCountDic.Add(PropItemEnum.xiaochu,0);
            mPropCountDic.Add(PropItemEnum.xipai,0);
            mPropCountDic.Add(PropItemEnum.fanpai,0);
            mPropCountDic.Add(PropItemEnum.citie,0);
            mPropCountDic.Add(PropItemEnum.huitui,0);
            mPropCountDic.Add(PropItemEnum.jiashi,0);

            OnEvent();
        }

        private float leijishijian = 0;
        void Update(float addtime)
        {
            mobjStart.SetActive(GameHelp.GamePause);
            mobjStop.SetActive(!GameHelp.GamePause);
            if (GameHelp.GamePause == false)
            {
                leijishijian += Time.deltaTime;
                if (leijishijian >= 1)
                {
                    mGameTimer--;
                    OnXuliehuaTimer();
                    leijishijian -= 1;
                    
                    if (mGameTimer <= 0)
                    {
                        //弹出看广告
                        GameHelp.GamePause = true;
                        GameHelp.CanRayCast = false;
                        UIManager.Instance.Show(ViewName.GameEndView, ViewLayer.Game,0);
                    }
                }
            }   
        }
        
        void OnInitData()
        {
            mPropCountDic[PropItemEnum.xiaochu] = 0;
            mPropCountDic[PropItemEnum.xipai] = 0;
            mPropCountDic[PropItemEnum.fanpai] = 0;
            mPropCountDic[PropItemEnum.citie] = 0;
            mPropCountDic[PropItemEnum.huitui] = 0;
            mPropCountDic[PropItemEnum.jiashi] = 0;
            
            var playerproitem = GameHelp.OnGetSelfPlayerPropItemTable();
            for (int i = 0; i < playerproitem.Count; i++)
            {
                if (mPropCountDic.ContainsKey(playerproitem[i].enumid))
                {
                    mPropCountDic[playerproitem[i].enumid]++;
                }
            }
            
            OnUpdateData();
        }
        
        void OnUpdateData()
        {
            int xiaochu = mPropCountDic[PropItemEnum.xiaochu];
            mOptArr[0]._objHaveTimes.SetActive(xiaochu >= 1);
            mOptArr[0]._objAddTimes.SetActive(xiaochu <= 0);
            mOptArr[0]._txtbacktimes.text = string.Format("x{0}", xiaochu);
            
            
            int xipai = mPropCountDic[PropItemEnum.xipai];
            mOptArr[1]._objHaveTimes.SetActive(xipai >= 1);
            mOptArr[1]._objAddTimes.SetActive(xipai <= 0);
            mOptArr[1]._txtbacktimes.text = string.Format("x{0}", xipai);
            
            
            int fanpai = mPropCountDic[PropItemEnum.fanpai];
            mOptArr[2]._objHaveTimes.SetActive(fanpai >= 1);
            mOptArr[2]._objAddTimes.SetActive(fanpai <= 0);
            mOptArr[2]._txtbacktimes.text = string.Format("x{0}", fanpai);
            
            
            int citie = mPropCountDic[PropItemEnum.citie];
            mOptArr[3]._objHaveTimes.SetActive(citie >= 1);
            mOptArr[3]._objAddTimes.SetActive(citie <= 0);
            mOptArr[3]._txtbacktimes.text = string.Format("x{0}", citie);
            
            
            int huitui = mPropCountDic[PropItemEnum.huitui];
            mOptArr[4]._objHaveTimes.SetActive(huitui >= 1);
            mOptArr[4]._objAddTimes.SetActive(huitui <= 0);
            mOptArr[4]._txtbacktimes.text = string.Format("x{0}", huitui);
            
            int jiashi = mPropCountDic[PropItemEnum.jiashi];
            mobjAddTime.SetActive(jiashi <= 0);
        }
        
        void OnEvent()
        {
            AddClickListener(mbtnStop,() =>
            {
                GameHelp.GamePause = !GameHelp.GamePause;
                if (GameHelp.GamePause)
                {
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.GamePauseView, ViewLayer.Middle);
                }
                Debug.LogError("状态："+GameHelp.GamePause+","+GameHelp.CanRayCast);
            });
            
            AddClickListener(mOptArr[0]._btn,() =>
            {
                Debug.Log("消除");

                if (mPropCountDic[PropItemEnum.xiaochu] > 0)
                {
                    int havezerocardbum = 0;
                    for (int i = 0; i < mShowCardNumArr.Length; i++)
                    {
                        if (mShowCardNumArr[i] <= 0)
                        {
                            havezerocardbum++;
                        }
                    }
                    if (havezerocardbum>=3)
                    {
                        //吸三张一样的牌过来
                        var xiaochulist = MJCtrl.Instance().OnGetLiveCardForXiaochu();
                        if (xiaochulist.Count >= 3)
                        {
                            for (int i = 0; i < xiaochulist.Count; i++)
                            {
                                int index = i;
                                int wait = 0;
                                DOTween.To(() => wait, x => wait = x, 10, (i+1)*0.3f).OnComplete(() =>
                                {
                                    ClickMjInfo info = new ClickMjInfo(
                                        xiaochulist[index].mMJCardNum,
                                        xiaochulist[index].mMJCardNumIndex,
                                        Vector3.zero, 
                                        xiaochulist[index]);
                                    OnOptSetCard(info);
                                });  
                            }
      
                            GameHelp.OnRemoveSelfPlayerPropItemById(new List<PropItemEnum>(){PropItemEnum.xiaochu});
                            mPropCountDic[PropItemEnum.xiaochu]--;
                            OnUpdateData();
                        }
                        else
                        {
                            UIManager.Instance.Show(ViewName.ToolTipsView, ViewLayer.Top, "桌面牌不足使用消除道具，使用失败！");
                            GameHelp.CanRayCast = true;
                        }
                    }
                    else
                    {
                        UIManager.Instance.Show(ViewName.ToolTipsView, ViewLayer.Top, "牌槽不足，使用失败！");
                        GameHelp.CanRayCast = true;
                    }
                    
                }
                else
                {
                    //打开，提问要不要去看广告界面
                    GameHelp.GamePause = true;
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.SeeAdvView, ViewLayer.Middle,PropItemEnum.xiaochu);
                }
            });
            AddClickListener(mOptArr[1]._btn,() =>
            {
                Debug.Log("洗牌");
                if (mPropCountDic[PropItemEnum.xipai] > 0)
                {
                    GameHelp.OnRemoveSelfPlayerPropItemById(new List<PropItemEnum>(){PropItemEnum.xipai});
                    mPropCountDic[PropItemEnum.xipai]--;
                    OnUpdateData();
                    
                    mFanpaiList = MJCtrl.Instance().OnXipai();
                    int wait = 0;
                    DOTween.To(() => wait, x => wait = x, 10, 0.5f).OnComplete(() =>
                    {
                        Utils.StartCoroutine(_OnStartGame());
                    });
                }
                else
                {
                    //打开，提问要不要去看广告界面
                    GameHelp.GamePause = true;
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.SeeAdvView, ViewLayer.Middle,PropItemEnum.xipai);
                }
            });
            AddClickListener(mOptArr[2]._btn, () =>
            {
                Debug.Log("翻牌");
                if (mPropCountDic[PropItemEnum.fanpai] > 0)
                {
                    MJCtrl.Instance().OnZhengli();
                    GameHelp.OnRemoveSelfPlayerPropItemById(new List<PropItemEnum>(){PropItemEnum.fanpai});
                    mPropCountDic[PropItemEnum.fanpai]--;
                    OnUpdateData();
                }
                else
                {
                    //打开，提问要不要去看广告界面
                    GameHelp.GamePause = true;
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.SeeAdvView, ViewLayer.Middle,PropItemEnum.fanpai);
                }
            });
            AddClickListener(mOptArr[3]._btn, () =>
            {
                Debug.Log("磁铁");
                if (mPropCountDic[PropItemEnum.citie] > 0)
                {
                    var citielist = MJCtrl.Instance().OnGetLiveCardForCitie();
                    if (citielist.Count >= 9)
                    {
                        for (int i = 0; i < citielist.Count; i++)
                        {
                            int index = i;
                            int wait = 0;
                            DOTween.To(() => wait, x => wait = x, 10, 0.3f).SetDelay(Random.Range(0.1f,0.4f)).OnComplete(() =>
                            {
                                ClickMjInfo info = new ClickMjInfo(
                                    citielist[index].mMJCardNum,
                                    citielist[index].mMJCardNumIndex,
                                    Vector3.zero, 
                                    citielist[index]);
                                OnOptSetCard_Citie(info);
                            });
                        }
  
                        GameHelp.OnRemoveSelfPlayerPropItemById(new List<PropItemEnum>(){PropItemEnum.citie});
                        mPropCountDic[PropItemEnum.citie]--;
                        OnUpdateData();
                    }
                    else
                    {
                        UIManager.Instance.Show(ViewName.ToolTipsView, ViewLayer.Top, "桌面牌不足使用磁铁道具，使用失败！");
                        GameHelp.CanRayCast = true;
                    }
                }
                else
                {
                    //打开，提问要不要去看广告界面
                    GameHelp.GamePause = true;
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.SeeAdvView, ViewLayer.Middle,PropItemEnum.citie);
                }
            });
            AddClickListener(mOptArr[4]._btn,() =>
            {
                Debug.Log("回退"+GameHelp.CanRayCast);
                if (mPropCountDic[PropItemEnum.huitui] > 0)
                {
                    bool showcardarrnoCard = false;
                    for (int i = 0; i < mShowCardNumArr.Length; i++)
                    {
                        if (mShowCardNumArr[i] > 0)
                        {
                            showcardarrnoCard = true;
                            break;
                        }
                    }
                    if (showcardarrnoCard)
                    {
                        OnBackOneCard();
                        GameHelp.OnRemoveSelfPlayerPropItemById(new List<PropItemEnum>(){PropItemEnum.huitui});
                        mPropCountDic[PropItemEnum.huitui]--;
                        OnUpdateData();
                    }
                    else
                    {
                        UIManager.Instance.Show(ViewName.ToolTipsView, ViewLayer.Top, "牌槽列表中暂无牌，无法使用道具，使用失败！");
                    }
                }
                else
                {
                    //打开，提问要不要去看广告界面
                    GameHelp.GamePause = true;
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.SeeAdvView, ViewLayer.Middle,PropItemEnum.huitui);
                }
            });
            AddClickListener(mbtnAddTime, () =>
            {
                Debug.Log("添加时间");
                if (mPropCountDic[PropItemEnum.jiashi] > 0)
                {
                    var proptable = GameLocalInfo.OnGetPropItemTableById(PropItemEnum.jiashi);
                    if (proptable != null)
                    {
                        mGameTimer += proptable.useadd;
                    }
                    
                    Debug.Log("添加时间"+ GameHelp.GameTimer+","+proptable.useadd);
                    GameHelp.OnRemoveSelfPlayerPropItemById(new List<PropItemEnum>(){PropItemEnum.jiashi});
                    mPropCountDic[PropItemEnum.jiashi]--;
                    OnUpdateData();
                }
                else
                {
                    //打开，提问要不要去看广告界面
                    GameHelp.GamePause = true;
                    GameHelp.CanRayCast = false;
                    UIManager.Instance.Show(ViewName.SeeAdvView, ViewLayer.Middle,PropItemEnum.jiashi);
                }
            });
        }

        private void OnBackOneCard()
        {
            int backcardnum = 0;
            int backindex = 0;
            for (int i = mShowCardNumArr.Length-1; i >= 0 ; i--)
            {
                if (mShowCardNumArr[i] > 0)
                {
                    backcardnum = mShowCardNumArr[i];
                    backindex = i;
                    mShowCardNumArr[i] = 0;
                    break;
                }
            }

            Debug.Log("回退"+backcardnum+","+backindex);
            if (backcardnum > 0)
            {
                //喷一个mj出去
                DoBackOneCardToTable(backcardnum, backindex);
                //整理面板
                OnSetCardFaceNum();
            }
        }
        
        // 一张
        void DoBackOneCardToTable(int whichOne,int indexx)
        {
            var mjcs = MJCtrl.Instance().OnGetOneDisLiveMJById(whichOne);
            Debug.LogError("fashed :"+mjcs.mMJCardNum);
            // mjcs.DoSetScale(1);
            mjcs.transform.position = OnGetItemPos(indexx);
            mjcs.AddFace(Random.Range(-70,70), 100,3);
            
            mCardNum++;
            mtxtCardNum.text = string.Format("x{0}", mCardNum);
        }
        
        void OnOptSetCard(ClickMjInfo info)
        {
            GameHelp.CanRayCast = false;
            MJCS mj = info.mjcs;
            
            //先检测是不是有相同的
            int addindex = OnCheckSame(info.mjNum);
            mj.DoSetScale(CardCao.Ins.OnGetCardScale());
            mj.DoMoveToPos(OnGetItemPos(addindex), () =>
            {
                GameHelp.CanRayCast = true;
                //整理结束之后在消失
                mj.OnSetDisLive();
                //根据检测完的数据整理一下牌面
                OnSetCardFaceNum();
                
                //如果满足就消失掉三个，整理一下，在根据整理的数据显示牌面
                int havethreesamecard = OnCheckSameThreeThenPass();
                if (havethreesamecard >= 0)
                {
                    OnXiaochu(havethreesamecard);
                }
                else
                {
                    //检测游戏是否结束
                    OnCheckGameEnd();

                    //最后检测一次格子是不是满了
                    OnCheckItemFull();
                }
            });
            mCardNum--;
            mtxtCardNum.text = string.Format("x{0}", mCardNum);
        }
        
        
        //使用磁铁函数
        void OnOptSetCard_Citie(ClickMjInfo info)
        {
            GameHelp.CanRayCast = false;
            MJCS mj = info.mjcs;
            
            //先检测是不是有相同的
            mj.DoMoveToPos(new Vector3(0,5,0), () =>
            {
                GameHelp.CanRayCast = true;
                //整理结束之后在消失
                mj.OnSetDisLive();
                
                //检测游戏是否结束
                OnCheckGameEnd();
            });
            mCardNum--;
            mtxtCardNum.text = string.Format("x{0}", mCardNum);
        }

        //返回一个可以添加格子的位置索引
        private int OnCheckSame(int cardnum)
        {
            int needbackindex = 0;
            int[] gezinew = new int[mShowCardNumArr.Length];
            for (int i = 0; i < gezinew.Length; i++)
            {
                gezinew[i] = 0;
            }
            
            for (int i = 0; i < mShowCardNumArr.Length; i++)
            {
                gezinew[i] = mShowCardNumArr[i];
                
                //有相同的牌面
                if (mShowCardNumArr[i] == cardnum)
                {
                    int nextsprite = (i + 1);
                    
                    if (OnCheckItemFull() == false)
                    {
                        //没满的时候加入格子内
                        gezinew[nextsprite] = cardnum;
                        
                        for (int j = nextsprite; j < mShowCardNumArr.Length; j++)
                        {
                            if (mShowCardNumArr[j] > 0)
                            {
                                gezinew[++nextsprite] = mShowCardNumArr[j];
                            }
                        }
                    }
                    break;
                }
                else
                {
                    if (mShowCardNumArr[i] <= 0)
                    {
                        gezinew[i] = cardnum;
                        needbackindex = i;
                        break;
                    }
                }
            }

            for (int i = mShowCardNumArr.Length-1; i >= 0; i--)
            {
                if (mShowCardNumArr[i] == cardnum)
                {
                    needbackindex = i + 1;
                    break;
                }
            }
            
            mShowCardNumArr = gezinew;
            
            return needbackindex;
        }

        //设置牌面
        private void OnSetCardFaceNum()
        {
            CardCao.Ins.OnUpdateCardFace(mShowCardNumArr);
            // for (int i = 0; i < mShowCardNumArr.Length; i++)
            // {
            //     mimgShowCard[i]._csMj.gameObject.SetActive(mShowCardNumArr[i] > 0);
            //     mimgShowCard[i]._csMj.OnSetMetail(MJCtrl.Instance().OnGetMaterialBymjId(mShowCardNumArr[i]));
            //     mimgShowCard[i]._csMj.transform.localPosition = Vector3.zero;
            //     // OnSetMetail
            //     // mimgShowCard[i].sprite = MJCtrl.Instance().OnGetMjSpriteByid(mShowCardNumArr[i]);
            // }
        }
        
        //检测是否满足三个 满足三个 需要消失
        private int OnCheckSameThreeThenPass()
        {
            int youjilu = 0;
            int jishu = 0;
            for (int i = 0; i < mShowCardNumArr.Length; i++)
            {
                if (mShowCardNumArr[i] > 0 && mShowCardNumArr[i] == youjilu)
                {
                    jishu++;
                    //连续三个满足
                    if (jishu >= 3)
                    {
                        // Debug.Log("满足三个 可以消失了"+youjilu);
                        //需要小时
                        break;
                    }
                }
                else
                {
                    youjilu = mShowCardNumArr[i];
                    jishu = 1;
                }
            }

            int havethreeandmiddleindex = -1;
            if (jishu >= 3)
            {
                int zhengliIndx = 0;
                int[] zhengli = new int[mShowCardNumArr.Length];
                for (int i = 0; i < mShowCardNumArr.Length; i++)
                {
                    if (havethreeandmiddleindex <= -1 && mShowCardNumArr[i] == youjilu)
                    {
                        havethreeandmiddleindex = i;
                    }
                    if (mShowCardNumArr[i] > 0 && mShowCardNumArr[i] != youjilu)
                    {
                        zhengli[zhengliIndx] = mShowCardNumArr[i];
                        zhengliIndx++;
                    }
                }
                mShowCardNumArr = zhengli;
                return havethreeandmiddleindex;
            }

            return havethreeandmiddleindex;
        }

        //满足三个消失，等待一下开始下一个
        private void OnXiaochu(int havethreesamecard)
        {
            CardCao.Ins.OnSetCardCaoXiaochu(havethreesamecard+1);
            // float paiendpos = mimgShowCard[havethreesamecard + 1]._csMj.transform.parent.transform.localPosition.x - mimgShowCard[havethreesamecard]._csMj.transform.parent.transform.localPosition.x;
            // mimgShowCard[havethreesamecard]._csMj.transform.DOLocalMoveX(paiendpos, 0.2f).SetEase(Ease.Linear).OnComplete(() =>
            // {
            //     mimgShowCard[havethreesamecard]._csMj.transform.localPosition = Vector3.zero;
            // });
            // mimgShowCard[havethreesamecard+2]._csMj.transform.DOLocalMoveX(-paiendpos, 0.2f).SetEase(Ease.Linear).OnComplete(() =>
            // {
            //     mimgShowCard[havethreesamecard+2]._csMj.transform.localPosition = Vector3.zero;
            // });
            //等一会做个延迟，消失
            int dengdai = 0;
            DOTween.To(() => dengdai, x => dengdai = x, 10, 0.2f).OnComplete(() =>
            {
                OnSetCardFaceNum();
                        
                //检测游戏是否结束
                OnCheckGameEnd();

                //最后检测一次格子是不是满了
                OnCheckItemFull();
                
                GameHelp.CanRayCast = true;
            });
        }
        
        //检测游戏是否结束
        private void OnCheckGameEnd()
        {
            if (!MJCtrl.Instance().OnTableHaveLiveCard())
            {
                TaskManager.OnAddTaskNumByTaskType(TaskTypeEnum.pass);
                GameHelp.GamePause = true;
                Debug.Log("游戏结束");
                GameHelp.CanRayCast = false;
                GameHelp.GameLevel++;
                if (GameHelp.GameLevel >= GameHelp.Game1SendCardCountList.Length)
                {
                    GameHelp.GameLevel = GameHelp.Game1SendCardCountList.Length - 1;
                }
                GameLocalInfo.OnGetCurTypeLevel(true);
                
                int dengdai = 0;
                DOTween.To(() => dengdai, x => dengdai = x, 10, 1).OnComplete(() =>
                {
                    EventCenter.BroadCast(EventUtils.EventType.EVENT_GAME_START);
                });

            }
        }

        //检测是不是满了 弹出提示
        private bool OnCheckItemFull()
        {
            bool isout = true;
            for (int i = 0; i < mShowCardNumArr.Length; i++)
            {
                if (mShowCardNumArr[i] <= 0)
                {
                    isout = false;
                    break;
                }
            }
            if (isout)
            {
                Debug.Log("格子满了，不可以再点击了");
                GameHelp.GamePause = true;
                GameHelp.CanRayCast = false;
                if (GameHelp.G1GameEndSeeAdv <= 0)
                {
                    UIManager.Instance.Show(ViewName.ReviveView,ViewLayer.Middle);
                }
                else
                {
                    UIManager.Instance.Show(ViewName.GameEndView,ViewLayer.Game,0);
                }
            }

            return isout;
        }

        //获取七个mj的位置
        private Vector3 OnGetItemPos(int addindex)
        {
            return CardCao.Ins.OnGetCardPosByIndex(addindex);
            // return new Vector3(-1.25f+addindex*0.4f, 2f, -2f);
        }
        
        private void OnBackThreeCard(int card)
        {
            //第三个  剔除三张
            if (card == 3)
            {
                int three = 3;
                for (int i = mShowCardNumArr.Length-1; i >= 0 ; i--)
                {
                    if (mShowCardNumArr[i] > 0)
                    {
                        DoBackOneCardToTable(mShowCardNumArr[i], i);
                        mShowCardNumArr[i] = 0;
                        three--;
                    }

                    if (three <= 0)
                    {
                        break;
                    }
                }
                
                //根据检测完的数据整理一下牌面
                OnSetCardFaceNum();
            }
        }


        private void OnUpdatePlayerItem(PropItemEnum index)
        {
            if (index == PropItemEnum.jiashi)
            {
                mGameTimer += GameHelp.GameTimer;
            }
            GameHelp.GamePause = false;
            OnXuliehuaTimer();
            OnInitData();
        }

        private void OnGameStart()
        {
            //先清理卡槽的牌
            for (int i = 0; i < mShowCardNumArr.Length; i++)
            {
                mShowCardNumArr[i] = 0;
            }
            OnSetCardFaceNum();
            
            //游戏开始 关卡 level
            OnStartGame();
        }
        
        public override void OnShow(params object[] args)
        {
            base.OnShow();
            GameHelp.mFarmeBox.SetActive(true);
            CardCao.Ins.OnShowCardCao(true);
            OnInitData();
            
            Utils.OnUpdate += Update;
            EventCenter.AddListener<ClickMjInfo>(EventUtils.EventType.EVENT_OPT_CLICK_CARD,OnOptSetCard);
            EventCenter.AddListener<int>(EventUtils.EventType.EVENT_LOGIN_INIT_LOAD_MJRES,OnBackThreeCard);
            EventCenter.AddListener<PropItemEnum>(EventUtils.EventType.EVENT_ADV_END_TO_GAME,OnUpdatePlayerItem);
            EventCenter.AddListener(EventUtils.EventType.EVENT_GAME_START,OnGameStart);
            
            GameHelp.GamePause = false;
            
            // GameHelp.GameLevel = 1;
            GameHelp.GameLevel = GameLocalInfo.OnGetCurTypeLevel();
            EventCenter.BroadCast(EventUtils.EventType.EVENT_GAME_START);
        }

        public override void OnClose(params object[] args)
        {
            base.OnClose();
            Utils.OnUpdate -= Update;
            if (gameObject.activeSelf)
            {
                EventCenter.RemoveListener<ClickMjInfo>(EventUtils.EventType.EVENT_OPT_CLICK_CARD,OnOptSetCard);
                EventCenter.RemoveListener<int>(EventUtils.EventType.EVENT_LOGIN_INIT_LOAD_MJRES,OnBackThreeCard);
                EventCenter.RemoveListener<PropItemEnum>(EventUtils.EventType.EVENT_ADV_END_TO_GAME,OnUpdatePlayerItem);
                EventCenter.RemoveListener(EventUtils.EventType.EVENT_GAME_START,OnGameStart);
            }
        }

        private void OnXuliehuaTimer()
        {
            if (mGameTimer >= 0)
            {
                string shijian = "";
                long hour = (int)((mGameTimer) / 3600);
                long min = (int)((mGameTimer - hour * 3600) / 60);
                long sen = (mGameTimer - hour * 3600 - min * 60);

                if (hour > 0)
                {
                    shijian += hour + "h:";
                }
            
                if (hour > 0 || min > 0)
                {
                    if (min <= 9)
                    {
                        shijian += string.Format("0{0}:", min);
                    }
                    else
                    {
                        shijian += string.Format("{0}:", min);
                    }
                }
                if (sen >= 0)
                {
                    if (sen <= 9)
                    {
                        shijian += string.Format("0{0}", sen);
                    }
                    else
                    {
                        shijian += string.Format("{0}", sen);
                    }
                }

                mtxtTime.text = shijian;
            }
            else
            {
                //游戏结束：
                OnCheckGameEnd();
            }
        }
        
        private void OnStartGame()
        {
            GameHelp.GamePause = true;
            // Debug.LogError("当前 1 关卡："+GameHelp.GameLevel+","+GameHelp.GameTimer+","+GameHelp.GamePause);
            OnUpdateData();
            GameHelp.OnInitRoom();
            mGameTimer = GameHelp.GameTimer;

            GameHelp.mFrameBoxGaizi.SetActive(false);
            MJCtrl.Instance().OnDesctroyCard();
            int mjcount = GameHelp.Game1SendCardCountList[GameHelp.GameLevel];
            mFanpaiList = MJCtrl.Instance().OnGetNeedShowMjList(mjcount,false);
            
            mCardNum = mFanpaiList.Count;
            mtxtCardNum.text = string.Format("x{0}", mCardNum);

            if (GameHelp.GameLevel == 1)
            {
                List<Vector3> poslist = new List<Vector3>()
                {
                    new Vector3(-1.2f, 0.5f, 1),
                    new Vector3(0, 0.5f, 1),
                    new Vector3(1.2f, 0.5f, 1),
                    new Vector3(-1.2f, 0.5f, 0),
                    new Vector3(0, 0.5f, 0),
                    new Vector3(1.2f, 0.5f, 0),
                    new Vector3(-1.2f, 0.5f, -1),
                    new Vector3(0, 0.5f, -1),
                    new Vector3(1.2f, 0.5f, -1)
                };
                for (int i = 0; i < mFanpaiList.Count; i++)
                {
                    mFanpaiList[i].OnSetSale(1);
                    mFanpaiList[i].OnShowCardBe(poslist[i].x, poslist[i].z, poslist[i].y, false);
                    mFanpaiList[i].DoRandomEulerAngles();
                }

                OnXuliehuaTimer();
                GameHelp.GamePause = false;
                GameHelp.CanRayCast = true;
            }
            else
            {
                GameHelp.mFrameBoxGaizi.SetActive(true);
                Utils.StartCoroutine(_OnStartGame());
            }
            GameHelp.CanRayCast = true;
        }

        IEnumerator _OnStartGame()
        {
            int posindex = 0;
            int hight = 0;
            List<Vector3> poslist = GameHelp.OnGetAllPos();

            Dictionary<int,List<Vector3>> hang1 = new Dictionary<int, List<Vector3>>(){{0,new List<Vector3>()},{1,new List<Vector3>()},{2,new List<Vector3>()},{3,new List<Vector3>()},{4,new List<Vector3>()}};
            Dictionary<int,List<Vector3>> hang2 = new Dictionary<int, List<Vector3>>(){{0,new List<Vector3>()},{1,new List<Vector3>()},{2,new List<Vector3>()},{3,new List<Vector3>()},{4,new List<Vector3>()}};
            Dictionary<int,List<Vector3>> hang3 = new Dictionary<int, List<Vector3>>(){{0,new List<Vector3>()},{1,new List<Vector3>()},{2,new List<Vector3>()},{3,new List<Vector3>()},{4,new List<Vector3>()}};
            Dictionary<int,List<Vector3>> hang4 = new Dictionary<int, List<Vector3>>(){{0,new List<Vector3>()},{1,new List<Vector3>()},{2,new List<Vector3>()},{3,new List<Vector3>()},{4,new List<Vector3>()}};
            Dictionary<int,List<Vector3>> hang5 = new Dictionary<int, List<Vector3>>(){{0,new List<Vector3>()},{1,new List<Vector3>()},{2,new List<Vector3>()},{3,new List<Vector3>()},{4,new List<Vector3>()}};
            Dictionary<int,List<Vector3>> hang6 = new Dictionary<int, List<Vector3>>(){{0,new List<Vector3>()},{1,new List<Vector3>()},{2,new List<Vector3>()},{3,new List<Vector3>()},{4,new List<Vector3>()}};
            int ceng = 0;
            for (int i = 0; i < poslist.Count; i++)
            {
                ceng = i / 48;
                if (i/8==0 || i/8==6 || i/8==12)
                {
                    hang1[ceng].Add(poslist[i]);
                }
                if (i/8==1 || i/8==7 || i/8==13)
                {
                    hang2[ceng].Add(poslist[i]);
                }
                if (i/8==2 || i/8==8  || i/8==14)
                {
                    hang3[ceng].Add(poslist[i]);
                }
                if (i/8==3 || i/8==9 || i/8==15)
                {
                    hang4[ceng].Add(poslist[i]);
                }
                if (i/8==4 || i/8==10 || i/8==16)
                {
                    hang5[ceng].Add(poslist[i]);
                }
                if (i/8==5 || i/8==11 || i/8==17)
                {
                    hang6[ceng].Add(poslist[i]);
                }
            }

            int cardindex = 0;
            // for (int i = 0; i < ceng; i++)
            {
                var hang1_list = hang1[0];
                var hang2_list = hang2[0];
                var hang3_list = hang3[0];
                var hang4_list = hang4[0];
                var hang5_list = hang5[0];
                var hang6_list = hang6[0];
                float gamelevel2sacle = 0.8f;

                for (int j = 8-1; j >= 0 ; j--)
                {
                    if (cardindex < mFanpaiList.Count && j < hang1_list.Count)
                    {
                        for (int k = 0; k < ceng; k++)
                        {
                            if (mFanpaiList.Count > cardindex)
                            {
                                mFanpaiList[cardindex].OnSetSale(gamelevel2sacle);
                                mFanpaiList[cardindex].transform.position = OnGetMjStartPos(hang1[k][j]);
                                mFanpaiList[cardindex].OnSetLive();
                                mFanpaiList[cardindex].OnLockRightBodyRotation(true);
                                mFanpaiList[cardindex].DoMovePosToFapai(OnGetMjEndPos(hang1[k][j]),
                                    OnGetMjMoveTimes(),OnGetMjWaitForMoveTimes());
                                cardindex++;
                            }
                        }
                    }
                
                    if (cardindex < mFanpaiList.Count && j < hang2_list.Count)
                    {
                        for (int k = 0; k < ceng; k++)
                        {
                            if (mFanpaiList.Count > cardindex)
                            {
                                mFanpaiList[cardindex].OnSetSale(gamelevel2sacle);
                                mFanpaiList[cardindex].transform.position = OnGetMjStartPos(hang2[k][j]);
                                mFanpaiList[cardindex].OnSetLive();
                                mFanpaiList[cardindex].OnLockRightBodyRotation(true);
                                mFanpaiList[cardindex].DoMovePosToFapai(OnGetMjEndPos(hang2[k][j]),
                                    OnGetMjMoveTimes(),OnGetMjWaitForMoveTimes());
                                cardindex++;
                            }
                        }
                    }
                
                    if (cardindex < mFanpaiList.Count && j < hang3_list.Count)
                    {
                        for (int k = 0; k < ceng; k++)
                        {
                            if (mFanpaiList.Count > cardindex)
                            {
                                mFanpaiList[cardindex].OnSetSale(gamelevel2sacle);
                                mFanpaiList[cardindex].transform.position = OnGetMjStartPos(hang3[k][j]);
                                mFanpaiList[cardindex].OnSetLive();
                                mFanpaiList[cardindex].OnLockRightBodyRotation(true);
                                mFanpaiList[cardindex].DoMovePosToFapai(OnGetMjEndPos(hang3[k][j]),
                                    OnGetMjMoveTimes(),OnGetMjWaitForMoveTimes());
                                cardindex++;
                            }
                        }
                    }
                    yield return new WaitForSeconds(0.1f);
                }
                
                for (int j = 0; j < 8; j++)
                {
                    if (cardindex < mFanpaiList.Count && j < hang4_list.Count)
                    {
                        for (int k = 0; k < ceng; k++)
                        {
                            if (mFanpaiList.Count > cardindex)
                            {
                                mFanpaiList[cardindex].OnSetSale(gamelevel2sacle);
                                mFanpaiList[cardindex].transform.position = OnGetMjStartPos(hang4[k][j]);;
                                mFanpaiList[cardindex].OnSetLive();
                                mFanpaiList[cardindex].OnLockRightBodyRotation(true);
                                mFanpaiList[cardindex].DoMovePosToFapai(OnGetMjEndPos(hang4[k][j]),
                                    OnGetMjMoveTimes(),OnGetMjWaitForMoveTimes());
                                cardindex++;
                            }
                        }
                    }
                
                    if (cardindex < mFanpaiList.Count && j < hang5_list.Count)
                    {
                        for (int k = 0; k < ceng; k++)
                        {
                            if (mFanpaiList.Count > cardindex)
                            {
                                mFanpaiList[cardindex].OnSetSale(gamelevel2sacle);
                                mFanpaiList[cardindex].transform.position = OnGetMjStartPos(hang5[k][j]);;
                                mFanpaiList[cardindex].OnSetLive();
                                mFanpaiList[cardindex].OnLockRightBodyRotation(true);
                                mFanpaiList[cardindex].DoMovePosToFapai(OnGetMjEndPos(hang5[k][j]),
                                    OnGetMjMoveTimes(), OnGetMjWaitForMoveTimes());
                                cardindex++;
                            }
                        }
                    }
                
                    if (cardindex < mFanpaiList.Count && j < hang6_list.Count)
                    {
                        for (int k = 0; k < ceng; k++)
                        {
                            if (mFanpaiList.Count > cardindex)
                            {
                                mFanpaiList[cardindex].OnSetSale(gamelevel2sacle);
                                mFanpaiList[cardindex].transform.position = OnGetMjStartPos(hang6[k][j]);;
                                mFanpaiList[cardindex].OnSetLive();
                                mFanpaiList[cardindex].OnLockRightBodyRotation(true);
                                mFanpaiList[cardindex].DoMovePosToFapai(OnGetMjEndPos(hang6[k][j]), 
                                    OnGetMjMoveTimes(), OnGetMjWaitForMoveTimes());
                                cardindex++;
                            }
                        }
                    }
                    yield return new WaitForSeconds(0.1f);
                }
            }

            GameHelp.mFrameBoxGaizi.SetActive(false);
            // OnSetCardFaceNum();
            
            // mGameTimer = GameHelp.GameTimer;
            OnXuliehuaTimer();
            GameHelp.GamePause = false;
            GameHelp.CanRayCast = true;
            
            
            // yield return new WaitForSeconds(0.2f);
            for (int i = 0; i < mFanpaiList.Count; i++)
            {
                mFanpaiList[i].OnLockRightBodyRotation(false);
                // mFanpaiList[i].OnLockRightBodyPositoion(false);
                mFanpaiList[i].OnRightBodyPositoionDown(false);
            }
        }

        private Vector3 OnGetMjStartPos(Vector3 pos)
        {
            Vector3 startpos = Vector3.zero;//pos - Vector3.zero;//hang1[i] * 0.5f;
            startpos *= 0.2f;
            startpos.y = 2.5f;

            return startpos;
        }

        private float OnGetMjMoveTimes()
        {
            return Random.Range(0.4f, 0.5f);
            // return 0.5f;
        }

        private float OnGetMjWaitForMoveTimes()
        {
            return Random.Range(0, 0.2f);
            // return 0;
        }

        private Vector3 OnGetMjEndPos(Vector3 startpos)
        {
            float posrandom = 0.2f;
            Vector3 endpos = startpos;

            endpos.x += Random.Range(-posrandom, posrandom);
            endpos.z += Random.Range(-posrandom, posrandom);
            if (endpos.x >= (1.9f))
            {
                endpos.x = 1.8f;
            }
            else if (endpos.x < -1.8f)
            {
                endpos.x = -1.8f;
            }

            // if (endpos.x >= 1.9f)
            // {
            //     Debug.LogError("位置是多少："+endpos);
            // }
            
            if (endpos.z < (3-5))
            {
                endpos.z = (3-5);
            }
            else if (endpos.z >= 3)
            {
                endpos.z = 3;
            }
            return endpos;
        }
    }
}
